<template>
  <div class="balance-container">
    <h2>账户余额</h2>
    
    <el-card class="balance-card" v-loading="loading.balance">
      <!-- 余额概览 -->
      <div class="balance-overview">
        <div class="balance-amount">
          <span class="label">当前余额：</span>
          <span class="amount">¥ {{ balance.toFixed(2) }}</span>
        </div>
        <el-button type="primary" @click="showRechargeDialog">充值</el-button>
      </div>

      <!-- 充值记录 -->
      <div class="section">
        <h3>充值记录</h3>
        <el-table 
          :data="rechargeRecords" 
          style="width: 100%" 
          v-loading="loading.rechargeRecords"
          :empty-text="rechargeRecords.length === 0 ? '暂无充值记录' : ''"
        >
          <el-table-column prop="time" label="充值时间" width="180"></el-table-column>
          <el-table-column prop="amount" label="充值金额" width="120">
            <template #default="{row}">
              ¥ {{ row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="method" label="支付方式"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{row}">
              <el-tag 
                :type="row.status === '成功' ? 'success' : row.status === '处理中' ? 'warning' : 'danger'"
              >
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 消费明细 -->
      <div class="section">
        <h3>消费明细</h3>
        <el-table 
          :data="expenseRecords" 
          style="width: 100%" 
          v-loading="loading.expenseRecords"
          :empty-text="expenseRecords.length === 0 ? '暂无消费记录' : ''"
        >
          <el-table-column prop="time" label="消费时间" width="180"></el-table-column>
          <el-table-column prop="amount" label="消费金额" width="120">
            <template #default="{row}">
              ¥ {{ row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="item" label="消费项目"></el-table-column>
        </el-table>
      </div>
      </el-card>

      <!-- 充值对话框 -->
      <el-dialog title="账户充值" v-model="rechargeDialogVisible" width="30%">
        <el-form :model="rechargeForm" label-width="100px">
          <el-form-item label="充值金额">
            <el-input-number 
              v-model="rechargeForm.amount" 
              :min="10" 
              :step="10"
              controls-position="right">
              <template #prefix>¥</template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="支付方式">
            <el-radio-group v-model="rechargeForm.method">
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="wechat">微信支付</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecharge" :loading="loading.recharge">确认充值</el-button>
        </template>
      </el-dialog>
  </div>
</template>

<script>
import { getUserBalance, getPaymentRecords, getTransactionRecords, createRechargeOrder } from '@/api/payment';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      balance: 0,
      rechargeRecords: [],
      expenseRecords: [],
      rechargeDialogVisible: false,
      rechargeForm: {
        amount: 10,
        method: 'alipay'
      },
      loading: {
        balance: false,
        rechargeRecords: false,
        expenseRecords: false,
        recharge: false
      }
    }
  },
  methods: {
    showRechargeDialog() {
      this.rechargeDialogVisible = true;
    },
    async submitRecharge() {
      try {
        this.loading.recharge = true;
        const { data } = await createRechargeOrder({
          amount: this.rechargeForm.amount,
          paymentMethod: this.rechargeForm.method
        });
        
        if (data.success) {
          ElMessage.success('充值订单创建成功');
          this.rechargeDialogVisible = false;
          
          // 如果有支付链接或二维码，可以在这里处理
          // 例如：跳转到支付页面或显示支付二维码
          
          // 刷新数据
          this.fetchBalanceData();
        } else {
          ElMessage.error(data.message || '充值失败');
        }
      } catch (error) {
        console.error('充值失败:', error);
        ElMessage.error('充值失败，请稍后重试');
      } finally {
        this.loading.recharge = false;
      }
    },
    async fetchBalanceData() {
      this.fetchBalance();
      this.fetchRechargeRecords();
      this.fetchExpenseRecords();
    },
    async fetchBalance() {
      try {
        this.loading.balance = true;
        const { data } = await getUserBalance();
        if (data.success) {
          this.balance = data.balance;
        } else {
          ElMessage.warning(data.message || '获取余额失败');
        }
      } catch (error) {
        console.error('获取余额失败:', error);
        ElMessage.error('获取余额失败，请稍后重试');
      } finally {
        this.loading.balance = false;
      }
    },
    async fetchRechargeRecords() {
      try {
        this.loading.rechargeRecords = true;
        const { data } = await getPaymentRecords();
        if (data.success) {
          this.rechargeRecords = data.payments.map(payment => ({
            id: payment.id,
            time: new Date(payment.createdAt).toLocaleString(),
            amount: payment.amount,
            method: payment.paymentMethod === 'alipay' ? '支付宝' : '微信支付',
            status: payment.status === 'completed' ? '成功' : 
                   payment.status === 'pending' ? '处理中' : '失败'
          }));
        } else {
          ElMessage.warning(data.message || '获取充值记录失败');
        }
      } catch (error) {
        console.error('获取充值记录失败:', error);
        ElMessage.error('获取充值记录失败，请稍后重试');
      } finally {
        this.loading.rechargeRecords = false;
      }
    },
    async fetchExpenseRecords() {
      try {
        this.loading.expenseRecords = true;
        const { data } = await getTransactionRecords();
        if (data.success) {
          this.expenseRecords = data.transactions.map(transaction => ({
            id: transaction.id,
            time: new Date(transaction.createdAt).toLocaleString(),
            amount: transaction.amount,
            item: transaction.material ? transaction.material.title : '未知素材'
          }));
        } else {
          ElMessage.warning(data.message || '获取消费记录失败');
        }
      } catch (error) {
        console.error('获取消费记录失败:', error);
        ElMessage.error('获取消费记录失败，请稍后重试');
      } finally {
        this.loading.expenseRecords = false;
      }
    }
  },
  mounted() {
    this.fetchBalanceData();
  }
}
</script>

<style scoped>
.balance-container {
  padding: 20px;
}
.balance-card {
  margin-top: 20px;
}
.balance-overview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.balance-amount .amount {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.section {
  margin-bottom: 30px;
}
</style>